package com.yyb.service.impl;

import com.github.pagehelper.Page;
import com.yyb.common.PageInfo;
import com.yyb.constants.CoreConstant;
import com.yyb.domain.SysDept;
import com.yyb.domain.SysRole;
import com.yyb.domain.SysUser;
import com.yyb.dto.SysUserAddDTO;
import com.yyb.dto.SysUserQueryDTO;
import com.yyb.dto.SysUserUpdateDTO;
import com.yyb.exception.BusinessException;
import com.yyb.mapper.SysDeptMapper;
import com.yyb.mapper.SysRoleMapper;
import com.yyb.mapper.SysUserMapper;
import com.yyb.service.SysUserService;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 
 * 
 * 
 */
@Service
public class SysUserServiceImpl extends BaseServiceImpl<SysUser> implements SysUserService {

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private SysDeptMapper sysDeptMapper;

    @Resource
    private SysRoleMapper sysRoleMapper;

    /**
     * 用户登录
     *
     * @param username
     * @param password
     * @return
     */
    @Override
    public SysUser login(String username, String password) {
        return sysUserMapper.login(username, password);
    }

    /**
     * 根据ID查询用户数据
     *
     * @param userId
     * @return
     */
    @Override
    public SysUser queryUserById(Long userId) {
        SysUser sysUser = this.sysUserMapper.selectByPrimaryKey(userId);
        if (!ObjectUtils.isEmpty(sysUser)) {
            //查询领导信息
            Long leaderId = sysUser.getLeaderId();
            if (!ObjectUtils.isEmpty(leaderId)) {
                SysUser leader = this.sysUserMapper.selectByPrimaryKey(leaderId);
                if (!ObjectUtils.isEmpty(leader)) {
                    sysUser.setLeaderName(leader.getNickName());
                }

            }
            //查询部门信息
            Long deptId = sysUser.getDeptId();
            if (!ObjectUtils.isEmpty(deptId)) {
                SysDept dept = this.sysDeptMapper.selectByPrimaryKey(deptId);
                if (!ObjectUtils.isEmpty(dept)) {
                    sysUser.setDeptName(dept.getDeptName());
                }
            }
        }
        return sysUser;
    }

    /**
     * 查询所有权限
     *
     * @return
     */
    @Override
    public List<String> queryAllPermissions() {
        return this.sysUserMapper.queryAllPermissions();
    }

    /**
     * 根据用户ID查询用户的权限
     *
     * @param userId
     * @return
     */
    @Override
    public List<String> queryPermissionsByUserId(Long userId) {
        return this.sysUserMapper.queryPermissionsByUserId(userId);
    }

    /**
     * 分页查询用户数据
     *
     * @param pageInfo
     * @return
     */
    @Override
    public PageInfo<SysUser, SysUserQueryDTO> getByPage(PageInfo<SysUser, SysUserQueryDTO> pageInfo) {
        //开启分页
        Page<SysUser> page = this.startPage(pageInfo.getPageNumber(), pageInfo.getPageSize());
        //查询
        List<SysUser> sysUserList = this.sysUserMapper.queryAllUsers(pageInfo.getParams());
        pageInfo.setTotalCount(page.getTotal());
        pageInfo.setTotalPage(page.getPages());
        if (CollectionUtils.isEmpty(sysUserList)) {
            return pageInfo;
        }
        //翻译sysUserList里面的SysUser的deptId--->deptName
        //翻译sysUserList里面的SysUser的leaderId-->leaderName
        //取出sysUserList里面所有deptId
        Set<Long> deptIds=sysUserList.stream().map(SysUser::getDeptId).collect(Collectors.toSet());
        //根据deptIds查询部门数据
        List<SysDept> deptList=this.sysDeptMapper.selectByPrimaryKeys(deptIds);
        //把deptList转成Map
        Map<Long,SysDept> sysDeptMap=deptList.stream().collect(Collectors.toMap(SysDept::getDeptId,sysDept -> sysDept));
        //取出sysUserList里面的所有leaderId
        Set<Long> leaderIds = sysUserList.stream().map(SysUser::getLeaderId).collect(Collectors.toSet());
        //根据leaderIds取出所有用户数据
        List<SysUser> leaderList=this.sysUserMapper.selectByPrimaryKeys(leaderIds);
        Map<Long, SysUser> userMap = leaderList.stream().collect(Collectors.toMap(SysUser::getUserId, sysUser -> sysUser));
        //组装数据
        sysUserList.forEach(sysUser -> {
            Long leaderId = sysUser.getLeaderId();
            Long deptId = sysUser.getDeptId();
            if (!ObjectUtils.isEmpty(leaderId)) {
                SysUser leader = userMap.get(leaderId);
                if (!ObjectUtils.isEmpty(leader)) {
                    sysUser.setLeaderName(leader.getNickName());
                }
            }
            if (!ObjectUtils.isEmpty(deptId)) {
                SysDept dept = sysDeptMap.get(deptId);
                if (!ObjectUtils.isEmpty(dept)) {
                    sysUser.setDeptName(dept.getDeptName());
                }
            }
        });
        //把sysUserList交给pageInfo
        pageInfo.setList(sysUserList);
        return pageInfo;
    }

    /**
     * 添加用户
     *
     * @param sysUserAddDTO
     * @return
     */
    @Override
    public int insert(SysUserAddDTO sysUserAddDTO) {
        SysUser sysUser=new SysUser();
        //copy
        BeanUtils.copyProperties(sysUserAddDTO,sysUser);
        //填充其它属性
        sysUser.setPassword(DigestUtils.md5DigestAsHex(CoreConstant.DEFAULT_PASSWORD.getBytes()));
        //创建人和创建时间
        sysUser.setCreateBy(getUsername());
        Date time = new Date();
        sysUser.setCreateTime(time);
        sysUser.setUpdateTime(time);
        sysUser.setUserType(CoreConstant.USER_TYPE_NORMAL);
        return this.sysUserMapper.insertSelective(sysUser);
    }

    /**
     * 修改用户
     *
     * @param sysUserUpdateDTO
     * @return
     */
    @Override
    public int updateByPrimaryKey(SysUserUpdateDTO sysUserUpdateDTO) {
        SysUser sysUser=new SysUser();
        //copy
        BeanUtils.copyProperties(sysUserUpdateDTO,sysUser);
        //修改人和修改时间
        Date time = new Date();
        sysUser.setUpdateTime(time);
        sysUser.setUpdateBy(getUsername());
        return this.sysUserMapper.updateByPrimaryKeySelective(sysUser);
    }

    /**
     * 删除用户
     *
     * @param userId
     * @return
     */
    @Override
    @Transactional
    public int deleteByPrimaryKey(Long userId) {
        //根据用户ID删除sys_user_role
        sysRoleMapper.deleteUserRoleByUserId(userId);
        return this.sysUserMapper.deleteByPrimaryKey(userId);
    }

    /***
     * 重置用户密码
     * @param userId
     * @return
     */
    @Override
    @Transactional
    public int resetPwd(Long userId) {
        SysUser sysUser = this.sysUserMapper.selectByPrimaryKey(userId);
        if (ObjectUtils.isEmpty(sysUser)) {
            throw new BusinessException("当前用户不存在");
        }
        sysUser.setPassword(DigestUtils.md5DigestAsHex(CoreConstant.DEFAULT_PASSWORD.getBytes()));
        return this.sysUserMapper.updateByPrimaryKeySelective(sysUser);
    }

    /**
     * 修改用户密码
     *
     * @param userId
     * @param newPassword
     * @return
     */
    @Override
    public int updateByPassword(Long userId, String newPassword) {
        SysUser sysUser=new SysUser();
        sysUser.setUserId(userId);
        sysUser.setPassword(DigestUtils.md5DigestAsHex(newPassword.getBytes()));
        return this.sysUserMapper.updateByPrimaryKeySelective(sysUser);
    }

    /**
     * 保存用户头像
     *
     * @param userId
     * @param path
     * @return
     */
    @Override
    public int uploadUserAvatar(Long userId, String path) {
        SysUser sysUser=new SysUser();
        sysUser.setUserId(userId);
        sysUser.setAvatar(path);
        return this.sysUserMapper.updateByPrimaryKeySelective(sysUser);
    }
}
